'use strict';

const Service = require('egg').Service;

class BannerService extends Service {
    /**
     * 查询列表
     *
     * @param {String} title @default null -名称
     * @param {Boolean} sort @default -1 -排序
     * @param {Number} page @default 1 -当前页
     * @param {Number} status @default null -状态
     * @param {Number} currentPage @default 10 -返回条数
     * @param {String} select @default null -要显示的key
     */
    async find({title = '', status = null, sort = -1, page = 1, currentPage = 10} = {}, select = null) {
        const {ctx} = this;
        const userpopulate = 'headImg role username name';

        const res = await ctx.model.Banner
            .find({status})
            .regex('title', title)
            .sort({createAt: sort})
            .skip((Number(page) - 1) * Number(currentPage))
            .limit(Number(currentPage))
            .populate('auth', userpopulate)
            .select(select);
        const count = await ctx.model.Banner.find().regex('title', title).count();
        return {
            count,
            page,
            list: res
        };
    }

    /**
     * 新增
     *
     * @param {String} title - 标题
     * @param {String} desc - 内容
     * @param {String} type - 类型 默认0
     * @param {String} status - 状态 默认下架
     * @param {String} href - 链接
     * @param {String} img - 图片
     */
    async create({title, desc, type = 0, status = 0, href, img} = {}) {
        const {ctx} = this;
        return await ctx.model.Banner.create({
            title,
            type,
            status,
            desc,
            href,
            img,
            auth: ctx.state.user._id
        });
    }

    /**
     * 修改
     *
     * @param {String} id -id
     * @param {Object} payload -修改条件
     */
    async update(id, payload = {}) {
        const {ctx} = this;
        const banner = await ctx.model.Banner.findById(id);
        if (!banner || banner.delete) {
            ctx.throw(404, '广告不存在或已被删除');
        }
        // 权限验证
        await ctx.powerValidate(banner.auth._id);

        payload.updateAt = Date.now();
        return await ctx.model.Banner.findByIdAndUpdate(id, payload);
    }

    /**
     * 删除
     *
     * @param {String} ids -id
     */
    async destroy(ids) {
        const {ctx} = this;
        let id = [];
        if (!Array.isArray(id)) {
            id.push(ids);
        }
        // 权限验证
        await ctx.powerValidate();
        return await ctx.model.Banner.deleteMany({_id: {$or: {id}}});
    }
}

module.exports = BannerService;
